//
//  FoundController.m
//  Otaku
//
//  Created by lanou3g on 16/5/12.
//  Copyright © 2016年 Liuwx. All rights reserved.
//

#import "FoundController.h"


#import "SearchController.h"


#import "ReadBaseModel.h"
#import "ReadBaseCell.h"
#import "TextModelCell.h"
#import "ImageModelCell.h"
#import "MullImageModelCell.h"




@interface FoundController ()
@property (nonatomic, strong) NSArray *array;

@property (nonatomic, strong) NSMutableArray *readingArray;


@end
static NSString *const resultId = @"FoundCell";
@implementation FoundController

- (void)dealloc {
    [self.tableView removeObserver:[self.tableView defaultHeader] forKeyPath:@"contentOffset"];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"早晚必读";
    [self loadData];
    self.readingArray = [NSMutableArray new];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"TextModelCell" bundle:nil] forCellReuseIdentifier:@"TextModel"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ImageModelCell" bundle:nil] forCellReuseIdentifier:@"ImageModel"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MullImageModelCell" bundle:nil] forCellReuseIdentifier:@"MullImageModel"];

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    __weak typeof(self) weakSelf = self;
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderDefault refreshingBlock:^{
        
        [weakSelf.readingArray removeAllObjects];
        [weakSelf.tableView reloadData];
        [weakSelf loadData];
        
    }];
    
    
    self.view.backgroundColor = [UIColor grayColor];
    UIImage *backImage = [UIImage imageNamed:@"head_bg.png"];
    
    [self.navigationController.navigationBar setBackgroundImage:backImage forBarMetrics:UIBarMetricsDefault];
    
    // 设置头像
    UIImage *searchImage = [UIImage imageNamed:@"foundsearch@2x.png"];
    // 还原头像
    UIImage *newSearchImage = [searchImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    // 设置自定义 item
    
    UIButton *searchBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
    
    [searchBtn setImage:newSearchImage forState:(UIControlStateNormal)];
    [searchBtn addTarget:self action:@selector(searchAction:) forControlEvents:(UIControlEventTouchUpInside)];
    self.navigationController.navigationBarHidden = NO;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:searchBtn];
    
    
    // 设置头像
    UIImage *nearImage = [UIImage imageNamed:@"DeleteData.png"];
    // 还原头像
    UIImage *newNearImage = [nearImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    // 设置自定义 item
    
    UIButton *nearBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width - 44, 0, 44, 44)];
    
    [nearBtn setImage:newNearImage forState:(UIControlStateNormal)];
    [nearBtn addTarget:self action:@selector(deleteAction:) forControlEvents:(UIControlEventTouchUpInside)];
    self.navigationController.navigationBarHidden = NO;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:nearBtn];
    
//    self.array = @[@"早晚",@"奇闻"];
    
    [self.navigationController.navigationBar setBackgroundImage:backImage forBarMetrics:UIBarMetricsDefault];
    UISegmentedControl *segmentedC = [[UISegmentedControl alloc]initWithItems:self.array];
    [segmentedC addTarget:self action:@selector(segmentedAction:) forControlEvents:UIControlEventValueChanged];
    
//    self.navigationItem.titleView = segmentedC;
    
    
}


// titleView 的事件
- (void)segmentedAction:(UISegmentedControl *)segment {
    switch (segment.selectedSegmentIndex) {
        case 0: {
            /// 早晚
            
            
//            [self.navigationController popViewControllerAnimated:YES];
        }
            break;
            
        case 1: {
            /// 奇闻
                      
            
        }
            break;
            
            
        default:
            break;
    }
    
    
    
}

- (void)loadData {
    [LWXNetWorkRequestManager requestURL:[NSURL URLWithString:READINGNECESSARY_URL] Method:LWX_GET Params:nil Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        if (data) {
        NSMutableDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dataDict = jsonDict[@"data"];
        for (NSDictionary *itemDict in dataDict[@"data"]) {
            if (itemDict[@"group"][@"text"] || itemDict[@"group"][@"large_image"][@"url_list"][0][@"url"]) {
                
            
            ReadBaseModel *model = [ReadBaseModel modelWithDictionary:itemDict];
            [self.readingArray addObject:model];
}
                      
        }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                // 手动停止加载、刷新
                [[self.tableView defaultHeader] endRefreshing];
            });
        
        }
    }];
}



// 搜索点击事件
- (void)searchAction:(UIButton *)btn {
    SearchController *searchVC = [[SearchController alloc]init];
    [self.navigationController pushViewController:searchVC animated:YES];
  
}

// 清除缓存
- (void)deleteAction:(UIButton *)btn {
    
    [[SDImageCache sharedImageCache] clearDisk];
    [[SDImageCache sharedImageCache] cleanDisk];
    [self.tableView reloadData];
    [self performSelectorOnMainThread:@selector(clearMemorySuccess) withObject:nil waitUntilDone:YES];

}


- (void)clearMemorySuccess {
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"清除缓存成功" preferredStyle:UIAlertControllerStyleAlert];
    [alertC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
    
    [self presentViewController:alertC animated:YES completion:nil];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return self.readingArray.count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *modelName = NSStringFromClass([self.readingArray[indexPath.row] class]);
    
    Class CellClass = NSClassFromString([modelName stringByAppendingString:@"Cell"]);
    
    return [CellClass cellHeight];

}



 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

 
     UITableViewCell *cell = [ReadBaseCell cellWithTableView:tableView Model:self.readingArray[indexPath.row] IndexPath:indexPath];
     
 return cell;
     
 }



/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
